<?php
	
	// PHP5 Implementation - uses MySQLi.
	// mysqli('localhost', 'yourUsername', 'yourPassword', 'yourDatabase');

	$db = new mysqli('localhost', 'mykaryoview' ,'genomes', 'mykaryoview');
        if(!$db) {
		// Show error if we cannot connect.
		echo 'ERROR: Could not connect to the database.';
	} else {
		// Is there a posted query string?
		if(isset($_POST['queryString'])) {
			$queryString = $db->real_escape_string($_POST['queryString']);
			
			// Is the string length greater than 0?
			
			if(strlen($queryString) >0) {

				if (preg_match("/^rs\d+/", $queryString)) {		
            $query= $db->query("SELECT id as name,chr,position as chr_start,position as chr_end FROM snp WHERE id LIKE '$queryString%' LIMIT 10");         
            while ($result = $query ->fetch_object()) {
            	  $start  = $result->chr_start - 5000;
            	  if($start < 0){ $start = 0;}
            	  $end    = $result->chr_end   + 5000;
                $coords = $result->chr.':'.$start.','.$end;           
                    echo '<li onClick="fill(\''.$result->name.'\',\''.$coords.'\');">'.$result->name.'</li>';
                  }   
					
				} elseif ($queryString) {	
						$query= $db->query("SELECT name,chr,chr_start,chr_end FROM hgnc_genes WHERE name LIKE '$queryString%' LIMIT 10");					
						while ($result = $query ->fetch_object()) {
								$coords = $result->chr.':'.$result->chr_start.','.$result->chr_end;						
			         			echo '<li onClick="fill(\''.$result->name.'\',\''.$coords.'\');">'.$result->name.'</li>';
			         		}					
				} else {
					echo 'ERROR: There was a problem with the query.';
				}
			} else {
				// Dont do anything.
			} // There is a queryString.
		} else {
			echo 'There should be no direct access to this script!';
		}
	}
?>
